#include "event_loop_thread_pool.h"
#include "assert.h"

EventLoopThreadPool::EventLoopThreadPool(EventLoop* baseLoop, int numThreads) : 
    baseLoop_(baseLoop), 
    started_(false), 
    numThreads_(numThreads), 
    next_loop_idx_(0)
{
  if (numThreads_ <= 0){
    abort();
  }
}

void EventLoopThreadPool::start()
{
  baseLoop_->AssertInLoopThread();
  started_ = true;
  for (int i = 0; i < numThreads_; ++i){
    std::shared_ptr<EventLoopThread> t(new EventLoopThread());
    threads_.push_back(t);
    // startLoop才真正起线程 
    loops_.push_back(t->startLoop());
  }
}

EventLoop* EventLoopThreadPool::getNextLoop()
{
  baseLoop_->AssertInLoopThread();
  assert(started_);
  // 这里loop赋值为baseLoop其实是处理numThreads为0的情况
  EventLoop *loop = baseLoop_;
  if (!loops_.empty()){
    loop = loops_[next_loop_idx_];
    next_loop_idx_ = (next_loop_idx_ + 1) % numThreads_;
  }
  return loop;
}